package com.fyzk.activity.setting;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.fyzk.base.BaseActivity;
import com.fyzk.activity.app.AppToast;
import com.fyzk.data.preference.MySharedPreferences;
import com.fyzk.dialog.SureDialog;
import com.tyjc.lottery.R;
import com.fyzk.net.Commands;
import com.fyzk.utils.ImageUtils;
import com.fyzk.utils.LogUtil;
import com.fyzk.view.TopTitleView;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.http.body.RequestBody;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import http.Common.CommandUtil;
import com.wf.domain.UrlDef;
import http.DataUtil.text.TextUtil;
import http.StringResultBean;

/**
 * Created by fanxs11 on 17/5/15.
 */
@ContentView(R.layout.ac_addfeedback)
public class AddFeedbackActivity extends BaseActivity{

    @ViewInject(R.id.addfeedback_topview)
    private TopTitleView topView;

    @ViewInject(R.id.addfeedback_et)
    private EditText et;

    @ViewInject(R.id.addfeedback_add_img)
    private ImageView add_iv;

    @ViewInject(R.id.addfeedback_img)
    private ImageView imageView;

    @ViewInject(R.id.addfeedback_close)
    private ImageView delete;

    @ViewInject(R.id.addfeedback_add_text)
    private TextView add_tv;

    private String imgPath = "";

    private static final int GET_PICTURE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        try {
            switch (requestCode) {
                case GET_PICTURE:
                    // TODO sent to crop
                    if (resultCode == 0) {
//                        this.finish();
                    } else {
                        Uri uri = data.getData();
                        imgPath = getRealFilePath(getContext(), uri);
                        LogUtil.d("path : "+imgPath);
                        addImage();
                    }
                    break;
                default:
                    break;
            }

        } catch (Exception e) {

        }

    }

    private void initView() {
        topView.setRightTxt("发表");
        topView.getRightTxt().setGravity(Gravity.RIGHT);
        topView.getRightTxt().setBackground(null);
        topView.setOnTitleClickListener(this);
        addImage();

        add_iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (imgPath.equals("")) {
                    getPictrue();
                }
            }
        });

        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imgPath = "";
                addImage();
            }
        });

    }

    private void addImage() {
        if (imgPath.equals("")) {
            add_iv.setVisibility(View.VISIBLE);
            add_tv.setVisibility(View.VISIBLE);
            imageView.setVisibility(View.GONE);
            delete.setVisibility(View.GONE);
        } else {
            add_iv.setVisibility(View.GONE);
            add_tv.setVisibility(View.GONE);
            imageView.setVisibility(View.VISIBLE);
            delete.setVisibility(View.VISIBLE);
            imageView.setImageBitmap(toRoundCornerImage(ImageUtils.getSmallBitmap(imgPath), 15));
        }
    }

    /**
     * 从相册获取
     */
    private void getPictrue() {
        try {
            Intent intent = new Intent(Intent.ACTION_PICK, null);
            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    "image/*");
            startActivityForResult(intent, GET_PICTURE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String getRealFilePath(final Context context, final Uri uri ) {
        if ( null == uri ) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if ( scheme == null )
            data = uri.getPath();
        else if ( ContentResolver.SCHEME_FILE.equals( scheme ) ) {
            data = uri.getPath();
        } else if ( ContentResolver.SCHEME_CONTENT.equals( scheme ) ) {
            Cursor cursor = context.getContentResolver().query( uri, new String[] { MediaStore.Images.ImageColumns.DATA }, null, null, null );
            if ( null != cursor ) {
                if ( cursor.moveToFirst() ) {
                    int index = cursor.getColumnIndex( MediaStore.Images.ImageColumns.DATA );
                    if ( index > -1 ) {
                        data = cursor.getString( index );
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    /**
     *  新增反馈
     */
    private void addFeedbackRequest() {
//        TelephonyManager TelephonyMgr = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
//        String imei = TelephonyMgr.getDeviceId();
        long timestamp = System.currentTimeMillis();
        String token = http.DataUtil.md5.MD5.toMd5(http.DataUtil.md5.MD5.toMd5((UrlDef.stringFromJNI() +
                timestamp).getBytes()).getBytes());
        try {
            JSONObject request_json = new JSONObject();
            request_json.put("token", MySharedPreferences.getInstance().getAuthtoken());
            request_json.put("time", System.currentTimeMillis());
            JSONObject data = new JSONObject();
            data.put("user_mark", token);
            data.put("min_id", 0);
            data.put("content", et.getText().toString());
            request_json.put("data", data);
            LogUtil.d("联网请求json:"+request_json.toString());
            RequestParams params = new RequestParams(UrlDef.FORUM_URL + Commands.ADDFEEDBACK);
            String img = "";
            if (!imgPath.equals("")) {
                img = ImageUtils.imageZoom(ImageUtils.getSmallBitmap(imgPath), 200);
            }

            params.setBodyContent("req="+ URLEncoder.encode(request_json.toString(), "UTF-8")+"&aws_upload_file="+URLEncoder.encode(img, "UTF-8"));
            RequestBody body = params.getRequestBody();
            body.setContentType("application/x-www-form-urlencoded");
            params.setRequestBody(body);

            sendRequest(HttpMethod.POST, CommandUtil.ADDFEEDBACK, params, true);
        } catch (JSONException e) {

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void onSuccess(int requestCode, StringResultBean resultBean, String result) {
        super.onSuccess(requestCode, resultBean, result);

        showSureDialog();
    }

    @Override
    protected void onFailure(int requestCode) {
        super.onFailure(requestCode);
    }

    SureDialog sureDialog;
    /**
     * 确认支付对话框
     */
    public void showSureDialog() {

        SureDialog.OnDialogOKCancleClickListener listener = new SureDialog.OnDialogOKCancleClickListener() {

            @Override
            public void onOKClick() {

                finish();
                sureDialog.dismiss();
            }

            @Override
            public void onCancleClick() {
                // TODO Auto-generated method stub
                sureDialog.dismiss();
            }
        };

        sureDialog = new SureDialog(this, listener, "您的反馈信息已提交!", "", "确定");

        sureDialog.show();
    }

    @Override
    public void onRightClick() {
        if (TextUtil.isEmpty(et.getText().toString().trim())) {
            AppToast.getToast().show("请输入您要反馈的信息");
            return;
        }
        if (et.getText().toString().trim().length() < 5) {
            AppToast.getToast().show("反馈信息不能少于5个字");
            return;
        }
        addFeedbackRequest();
    }

    /**
     * 获取圆角位图的方法
     *
     * @param bitmap
     *            需要转化成圆角的位图
     * @param pixels
     *            圆角的度数，数值越大，圆角越大
     * @return 处理后的圆角位图
     */
    public static Bitmap toRoundCornerImage(Bitmap bitmap, int pixels) {
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);
        final float roundPx = pixels;
        // 抗锯齿
        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);
        return output;
    }

}
